//
//  WithdrawViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/16.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
class WithdrawViewController: BaseViewController {

    @IBOutlet var balanceLabel: UILabel!
    
    @IBOutlet var bankNumTF: UITextField!
    
    
    @IBOutlet var belongToBankNameTF: UITextField!
    
    @IBOutlet var bankUserNameTF: UITextField!
    
    
    @IBOutlet var IdCardTF: UITextField!
    
    
    @IBOutlet var withdrawMoneyTF: UITextField!
    
    @IBOutlet var phoneTF: UITextField!
    
    
    @IBOutlet var passwordTF: UITextField!
    
    @IBOutlet var remarkTF: UITextField!
    
    
    @IBOutlet var withdrawBtn: UIButton!
    
    var userBalance = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        updateVC()
        requestGetUserMoney()
        bankNumTF.delegate = self as UITextFieldDelegate
        baseSetNavRightButtonWithTitle("提现记录")
        
    }
    override func baseNavRightButtonPressed(_ button: UIButton) {
        let withdrawHistoryVC = WithdrawHistoryViewController()
        withdrawHistoryVC.title = "提现记录"; self.navigationController?.pushViewController(withdrawHistoryVC, animated: true)
    }

    func updateVC() -> Void {
        let bankNumStr = UserDefaults.standard.value(forKey: "bankNum")
        
        let belongToBankNameStr = UserDefaults.standard.value(forKey: "belongToBankName")
        
        let bankUserNameStr = UserDefaults.standard.value(forKey: "bankUserName")
        
        let IdCardStr = UserDefaults.standard.value(forKey: "IdCard")
        
        if bankNumStr != nil {
            bankNumTF.text = bankNumStr as? String
        }
        if belongToBankNameStr != nil {
            belongToBankNameTF.text = belongToBankNameStr as? String
        }
        if bankUserNameStr != nil {
            bankUserNameTF.text = bankUserNameStr as? String
        }
        if IdCardStr != nil {
            IdCardTF.text = IdCardStr as? String
        }
        
    }
    
    @IBAction func withdrawBtnPress(_ sender: UIButton) {
        if bankNumTF.text! == "" || belongToBankNameTF.text! == "" || bankUserNameTF.text! == "" || withdrawMoneyTF.text! == "" || phoneTF.text! == "" || passwordTF.text! == "" || IdCardTF.text! == "" {
            MBProgressHUD.alertShow(in: self.view, message: "请填写完整再发布", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            return
        }
       let withdrawMoney = Int(withdrawMoneyTF.text!)
        if (withdrawMoney! > userBalance){
            MBProgressHUD.alertShow(in: self.view, message: "提现金额超出账户余额，请重新填写", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            return
        }
        if withdrawMoney! < 100 {
            MBProgressHUD.alertShow(in: self.view, message: "提现金额至少100元，请重新填写", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            return
        }
        requestWithdraw()
    }
    
    
    //网络请求
    //获取账户余额
    func requestGetUserMoney() -> Void {
        Alamofire.request(getUserMoneyUrl, method:.post, parameters:["sid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        if basemodel.data?.balance != nil{
                            let balanceStr = "\((basemodel.data?.balance)!)"
                            self.balanceLabel.text =  balanceStr + "元"
                            
                            self.userBalance = lround((basemodel.data?.balance)!)
                            
                        }
                     
                    case false:
                        MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    //提现
    func requestWithdraw() -> Void {
        
        let param =
            ["cardno":bankNumTF.text!,
        
        "bank_name":belongToBankNameTF.text!,
             "cardname":bankUserNameTF.text!,
             "id_number":IdCardTF.text!,
             "price":withdrawMoneyTF.text!,
             "phone":phoneTF.text!,
             "remarks":remarkTF.text!,
             "paypassword":passwordTF.text!,
             "uid":UserModel.shareUser.data?.uid  ?? String(),
             "sid":UserModel.shareUser.data?.storeId  ?? String()] as [String : Any]
        
        Alamofire.request(withdrawUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                        hud?.mode = MBProgressHUDMode.text
                        hud?.labelText = "申请成功"
                        hud?.show(animated: true, whileExecuting: {                        Thread.sleep(forTimeInterval: 0.8)
                            
                        }, completionBlock: {
                        UserDefaults.standard.set(self.bankNumTF.text, forKey: "bankNum")
                        UserDefaults.standard.set(self.belongToBankNameTF.text, forKey: "belongToBankName")
                        UserDefaults.standard.set(self.bankUserNameTF.text, forKey: "bankUserName")
                            
                        UserDefaults.standard.set(self.IdCardTF.text, forKey: "IdCard")
                       
                        self.navigationController?.popViewController(animated: true)
                        })
                    case false:
                        MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension WithdrawViewController:UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField.tag == 111 {
            self.belongToBankNameTF.text = NSString.getBankName(textField.text)
        }
    }
    
}
